package com.bys.admin.system.convert.codegenTable;

import com.baomidou.mybatisplus.generator.config.po.TableField;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.bys.admin.system.controller.vo.CodegenTablePreviewResVO;
import com.bys.admin.system.entity.SysCodegenColumn;
import com.bys.admin.system.entity.SysCodegenTable;
import com.bys.util.CollectionUtils;
import org.apache.ibatis.type.JdbcType;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.Mappings;
import org.mapstruct.Named;
import org.mapstruct.factory.Mappers;

import java.util.List;
import java.util.Map;

@Mapper
public interface CodegenTableConvert {
    CodegenTableConvert INSTANCE = Mappers.getMapper(CodegenTableConvert.class);

    @Mappings({
            @Mapping(source = "name", target = "tableName"),
            @Mapping(source = "comment", target = "tableComment"),
    })
    SysCodegenTable convert(TableInfo bean);

    List<SysCodegenColumn> convertList(List<TableField> tableFields);

    @Mappings({
            @Mapping(source = "name", target = "columnName"),
            @Mapping(source = "metaInfo.jdbcType", target = "dataType", qualifiedByName = "getDataType"),
            @Mapping(source = "comment", target = "columnComment"),
            @Mapping(source = "metaInfo.nullable", target = "nullable"),
            @Mapping(source = "keyFlag", target = "primaryKey"),
            @Mapping(source = "columnType.type", target = "javaType"),
            @Mapping(source = "propertyName", target = "javaField"),
    })
    SysCodegenColumn convert(TableField bean);


    @Named("getDataType")
    default String getDataType(JdbcType jdbcType) {
        return jdbcType.name();
    }

    default List<CodegenTablePreviewResVO> convertPreviewVo(Map<String, String> codes) {
        return CollectionUtils.convertList(codes.entrySet(),
                entry -> CodegenTablePreviewResVO.builder().filePath(entry.getKey()).code(entry.getValue()).build());
    }
}
